package model.inventory;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import util.PlayerUtilities;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class InventoryItem {
	public static final String UNIQUE_VIHECLE_ID_STRING = "z_vehicleid_pk";
	// use a JSONObject as internal structure for storing data.
	private JSONObject data;

	// default constructor that contains no field mapping
	public InventoryItem() {
		this.data = new JSONObject();
	}

	public static Map<String, InventoryItem> getInventoryMapFromCSV(String fileName) {
		Map<String, InventoryItem> inventoryList = new HashMap<String, InventoryItem>();

		if (!new File(fileName).exists()) {
			return inventoryList;
		}

		List<String[]> csvData = PlayerUtilities.getArrayFromCSVFile(fileName);
		String[] fields = csvData.remove(0);
		for (String[] inventoryData : csvData) {
			InventoryItem item = new InventoryItem();
			for (int i = 0; i < inventoryData.length; i++) {
				item.setFieldData(fields[i], inventoryData[i]);
			}
			inventoryList.put(item.get(UNIQUE_VIHECLE_ID_STRING), item);
		}
		return inventoryList;
	}

	// designated constructor that will take a json string
	// precondition: jsonString is a valid JSON string
	// postcondition: the fields of this inventory item will be set
	public InventoryItem(String jsonString) {
		this.data = (JSONObject) JSONValue.parse(jsonString);
	}

	public void setFieldData(Object field, Object data) {
		this.data.put(field, data);
	}

	public String get(String field) {
		return (String)this.data.get(field);
	}

	@Override
	public String toString() {
		return this.data.toString();
	}

	public int getNumberOfFields() {
		return this.data.size();
	}

	@Override
	public boolean equals(Object o) {
		if (o instanceof InventoryItem) {
			InventoryItem ii = (InventoryItem) o;
			Object myId = this.get("z_vehicleid_pk");
			Object oId = ii.get("z_vehicleid_pk");

			if (myId == null || oId != null) {
				return false;
			} else {
				if (myId.equals(oId)) {
					return true;
				} else {
					return false;
				}
			}
		}

		return false;
	}

	@Override
	public int hashCode() {
		return 0;
	}

	// precondition: this.data is not null
	// postcondition: returns the "pictureN" from data
	public Object getPicture(int number) {
		return this.data.get("picture" + number);
	}

	public boolean isImageField(String fieldName) {
		return fieldName.contains("picture");
	}

	public String[] getFieldNames() {
		return (String[]) this.data.keySet().toArray(new String[] {});
	}
}
